﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;

namespace BoringTodo
{
    static class Program
    {
        private static Mutex singleInstanceMutex;
        private static bool isFirstInstance;
        
        [DllImport("user32.dll")]
        private static extern bool SetProcessDPIAware();

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                // 确保只有一个实例运行
                singleInstanceMutex = new Mutex(true, "BoringTodoApplicationMutex", out isFirstInstance);
                
                if (!isFirstInstance)
                {
                    MessageBox.Show("程序已经在运行中。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                
                // 初始化日志系统
                Logger.Initialize();
                Logger.Log("应用程序启动", LogLevel.Info);
                
                // 在程序一开始就设置进程为DPI感知
                try 
                {
                    SetProcessDPIAware();
                    // 关闭Windows特有的DPI仿真
                    Application.SetCompatibleTextRenderingDefault(false);
                }
                catch
                {
                    // 忽略可能的异常
                }
                
                Application.EnableVisualStyles();
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

                // 添加全局异常处理
                Application.ThreadException += Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                
                // 创建必要的文件夹
                EnsureAppFoldersExist();

                if (args.Length > 0)
                {
                    ProcessCommandLineArguments(args);
                }
                else
                {
                    // 正常启动应用程序
                    using (Form1 mainForm = new Form1())
                    {
                        Application.Run(mainForm);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                // 关闭日志系统
                Logger.Shutdown();
                
                // 释放单例互斥锁
                singleInstanceMutex?.ReleaseMutex();
                singleInstanceMutex?.Dispose();
            }
        }
        
        private static void ProcessCommandLineArguments(string[] args)
        {
            if (args[0].Equals("screenshot", StringComparison.OrdinalIgnoreCase))
            {
                // 设置DPI感知，用于正确截图
                SetProcessDPIAware();
                
                try
                {
                    // 创建一个临时的屏幕截图实例来执行截图
                    string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    ScreenShot screenshotInstance = new ScreenShot(myDocumentsPath);
                    var task = screenshotInstance.CaptureAndSaveAsync();
                    task.Wait(); // 等待截图完成
                    Logger.Log("通过命令行参数执行截图成功", LogLevel.Info);
                }
                catch (Exception ex)
                {
                    Logger.LogError("通过命令行参数执行截图失败", ex);
                }
            }
            else if (args[0].Equals("backup", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    // 创建数据备份
                    string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    DataManager dataManager = new DataManager(myDocumentsPath);
                    
                    // 加载并立即保存数据以创建备份
                    var normalTasks = dataManager.LoadData(Constants.NormalTasksFile);
                    var completedTasks = dataManager.LoadData(Constants.CompletedTasksFile);
                    
                    dataManager.SaveData(Constants.NormalTasksFile, normalTasks);
                    dataManager.SaveData(Constants.CompletedTasksFile, completedTasks);
                    
                    Logger.Log("通过命令行参数创建备份成功", LogLevel.Info);
                }
                catch (Exception ex)
                {
                    Logger.LogError("通过命令行参数创建备份失败", ex);
                }
            }
        }
        
        private static void EnsureAppFoldersExist()
        {
            try
            {
                string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string appDataFolder = Path.Combine(myDocumentsPath, Constants.AppDataFolder);
                
                // 创建主文件夹
                if (!Directory.Exists(appDataFolder))
                {
                    Directory.CreateDirectory(appDataFolder);
                    Logger.Log($"创建应用程序主文件夹: {appDataFolder}", LogLevel.Info);
                }
                
                // 创建截图文件夹
                string screenshotsFolder = Path.Combine(appDataFolder, Constants.ScreenshotsFolder);
                if (!Directory.Exists(screenshotsFolder))
                {
                    Directory.CreateDirectory(screenshotsFolder);
                    Logger.Log($"创建截图文件夹: {screenshotsFolder}", LogLevel.Info);
                }
                
                // 创建备份文件夹
                string backupFolder = Path.Combine(appDataFolder, Constants.BackupFolder);
                if (!Directory.Exists(backupFolder))
                {
                    Directory.CreateDirectory(backupFolder);
                    Logger.Log($"创建备份文件夹: {backupFolder}", LogLevel.Info);
                }
                
                // 创建日志文件夹
                string logsFolder = Path.Combine(appDataFolder, Constants.LogsFolder);
                if (!Directory.Exists(logsFolder))
                {
                    Directory.CreateDirectory(logsFolder);
                    Logger.Log($"创建日志文件夹: {logsFolder}", LogLevel.Info);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError("创建应用程序文件夹失败", ex);
                MessageBox.Show(
                    $"无法创建应用程序文件夹，程序可能无法正常工作。\n\n错误: {ex.Message}",
                    "初始化错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                );
            }
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private static void HandleException(Exception ex)
        {
            if (ex == null) return;
            
            try
            {
                Logger.LogError("未处理的异常", ex);
            }
            catch (Exception logEx)
            {
                // 如果日志记录失败，使用调试输出
                System.Diagnostics.Debug.WriteLine($"日志记录失败: {logEx.Message}");
                System.Diagnostics.Debug.WriteLine($"原始异常: {ex.Message}");
            }
            
            // 显示友好的错误消息
            MessageBox.Show(
                $"程序遇到了一个问题，已记录错误信息。\n\n错误: {ex.Message}\n\n如果此问题持续出现，请重启应用程序。",
                "程序错误",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error
            );
        }
    }
}
